package com.mindbook.testredis.controller;

import com.mindbook.testredis.entity.UserVo;
import com.mindbook.testredis.utils.RandomUtil;
import com.mindbook.testredis.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * 使用Redis的接口
 */
@RestController
@RequestMapping("redis")
public class RedicController {

    private static final int ExpireTime = 30; //设置redis中缓存时间为30秒

    @Autowired private RedisUtil redisUtil;

    @GetMapping("save")
    private String save(@RequestParam(required = true) String key, String value){
        boolean set = false;
        for(int i=0;i<1000;i++){
            UserVo userVo = new UserVo();
            userVo.setName("吴晓波");
            userVo.setAddress("北京昌平区");
            userVo.setAge(11);
            if(value!=null&&!"".equals(value)){
                set = redisUtil.set(key+i, value,ExpireTime);
            }else{
                set = redisUtil.set(key+i, userVo,ExpireTime);
            }
        }
        return set+"";
    }

    /**
     * 撑爆redis
     * @return
     */
    @GetMapping("insertList")
    private String saveHeaveData(){
        System.out.println("添加大量数据撑破redis");
        for(int i=0;i<1000;i++){
            String guid = RandomUtil.getGUID();
            redisUtil.set(guid+"i",guid,ExpireTime);
        }
        return "执行完成";
    }

    /**
     * 获取与key值对应的value值
     * @param key
     * @return
     */
    @GetMapping("get")
    private Object get(String key){
        return redisUtil.get(key);
    }

    /**
     * 查询key值是否还在有效期内
     * @param key
     * @return
     */
    @GetMapping("expire")
    private String expire(String key){
        boolean expire = redisUtil.expire(key, ExpireTime);
        return expire+"";
    }

    @DeleteMapping("delete")
    private String delete(String key){
        redisUtil.del(key);
        return "执行完成";
    }

}
